<template>
	<el-dialog :visible.sync="visible" destroy-on-close top="8vh" :title="!playId ? '添加剧集' : '修改剧集'"
		:close-on-click-modal="false" :close-on-press-escape="false" width="650px" @close="closeFn">
		<el-dialog class="innerDialog" v-dialogDrag width="650px" :title="playTitle+'  封面图'"
			:visible.sync="innerCoverVisible" append-to-body>
			<div class="d-flex a-cneter j-center pb-20">
				<el-image :style="{width: '650px',height: '450px'}" :src="clickImg" fit="scale-down"></el-image>
			</div>
		</el-dialog>
		
		<el-dialog class="innerDialog" v-dialogDrag :close-on-click-modal="false" width="500px"
			:title="(playTitle||'')+'  下载进度'" :visible.sync="innerDownloadVisible" append-to-body>
			<div class="d-flex flex-column mr-10">
				<div class="d-flex mb-5" style="font-size: 15px;">下载中，请稍后...</div>
				<el-progress :text-inside="false" :stroke-width="18" text-color="#409eff"
					:percentage="downloadPercentage"></el-progress>
				<div style="height: 30px;"></div>
			</div>
		</el-dialog>

		<el-dialog class="innerDialog" v-dialogDrag @close="closeVideoDialogFn" width="650px" :title="playTitle||'视频'"
			:visible.sync="innerPlayVisible" append-to-body>
			<div class="playerMain">
				<d-player class="dplayer" :options="videoOptions" ref="player"></d-player>
			</div>
		</el-dialog>

		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px" size="medium"
			:inline="false" labelSuffix="：">
			<el-form-item prop="playlet_number_name" label="剧集集数名称">
				<el-input clearable v-model="dataForm.playlet_number_name" placeholder="剧集集数名称" />
			</el-form-item>

			<el-form-item prop="playlet_id" label="短剧">
				<el-select clearable v-model="dataForm.playlet_id" placeholder="请选择" @focus="playletListFn"
					@change="changeSelectFn(dataForm.playlet_id,'playlet_id')">
					<el-option v-for="(item,index) in playletList" :key="index" :label="item.label"
						:value="item.value"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item prop="cover" label="封面图片">
				<div class="d-flex">
					<img v-if="dataForm.cover" class="d-flex mr-20 pointer" :src="dataForm.cover"
						@click.stop="lookImg(dataForm.cover)" style="width: 80px;height: auto;border-radius: 5px;">
					<div v-if="showimagesProgress" class="d-flex flex-column j-center mr-20">
						<div class="d-flex mb-5 mr-10">
							上传中，请稍后...
						</div>
						<el-progress :text-inside="false" :stroke-width="18" text-color="#409eff"
							:percentage="percentage"></el-progress>
					</div>
					<div class="d-flex a-center">
						<el-button style="width: 100px;height: 40px;"
							@click="uploadBtnFn('coverFileBtn','cover')">上传图片</el-button>
						<input type="file" ref="coverFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images')" />
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="play_url" label="短剧集数视频">
				<div class="d-flex">
					<div v-if="dataForm.play_url" class="d-flex a-center j-center position-relative mr-20 pointer"
						@click.stop="playVideo()">
						<img class="d-flex"
							:src="dataForm.play_url+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto'"
							style="width: 80px;height: auto;filter: opacity(0.7);border-radius: 5px;">
						<d2-icon class="d-flex position-absolute" name="play-circle-o"
							style="font-size: 30px;color: #379aff;" />
					</div>
					<div v-if="showvideosProgress" class="d-flex flex-column j-center mr-20">
						<div class="d-flex mb-5 mr-10">
							上传中，请稍后...
						</div>
						<el-progress :text-inside="false" :stroke-width="18" text-color="#409eff"
							:percentage="percentage"></el-progress>
					</div>
					<div class="d-flex a-center">
						<el-button style="width: 100px;height: 40px;"
							@click="uploadBtnFn('videoFileBtn','play_url')">上传视频</el-button>
						<input type="file" ref="videoFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'videos')" />
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="playlet_number" label="短剧集数">
				<el-input clearable v-model="dataForm.playlet_number"
					@input="(v)=>(dataForm.playlet_number=handleNumber1(v))" placeholder="短剧集数" />
			</el-form-item>
	
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash'
	import {
		handleNumber1,
		handleNumber2
	} from '@/libs/validate'
	import schema from 'async-validator'
	import uploadTools from "./uploadTools";
	import * as clipboard from 'clipboard-polyfill'
	import VueDPlayer from '@/libs/vue-dplayer';
	require("/src/assets/style/vue-dplayer.css");
	export default {
		components: {
			'd-player': VueDPlayer,
		},
		mixins: [uploadTools],
		data() {
			return {
				player: '',
				handleNumber1,
				handleNumber2,
				innerCoverVisible: false,
				innerPlayVisible: false,
				showimagesProgress: false,
				showvideosProgress: false,
				downloadPercentage: 0,
				percentage: 0,
				playId: null,
				clickImg: '',
				playTitle: '',
				field: '',
				innerDownloadVisible: false, //是否显示下载视频进度
				playletList: [], //短剧列表数据
				payType: [{
						value: 1,
						label: '免费',
					},
					{
						value: 2,
						label: '章节付费',
					}
				],
				status: [{
						value: 0,
						label: '禁用',
					},
					{
						value: 1,
						label: '正常',
					}
				],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				allEpisodeList: [],
				videoOptions: {
					video: {
						url: '', //视频链接
						pic: '', //封面图
						thumbnails: '' //缩略图
					},
					theme: '#409eff', //主题色
					screenshot: true, //是否支持截图
					autoplay: true, //是否自动播放
					preload: 'auto', //预加载
					contextmenu: [
						{
							text: '下载视频',
							click: (e) => {
								this.downloadVideo();
							},
						},
						{
							text: '复制视频地址',
							click: (e) => {
								if(this.videoOptions.video.url){
									this.copyText(this.videoOptions.video.url);
									return;
								}
								this.$message({
									message: '复制失败！视频地址为空！',
									type: 'error',
									duration: 1500
								})
							},
						},
					]
				},
				dataForm: {
					playlet_number_name: '', //剧集集数名称
					playlet_id: '', //短剧ID
					cover: '', //短剧集数封面图
					play_url: '', //短剧集数视频路径
					playlet_number: '', //短剧集数
					amount: '', //价格
				}
			}
		},
		created() {
			that = this;
		},
		computed: {
			dataRule() {
				return {
					playlet_number_name: [{
						required: true,
						message: '剧集集数名称不能为空!',
						trigger: ['blur', 'change']
					}],
					playlet_id: [{
						required: true,
						message: '短剧不能为空!',
						trigger: ['blur', 'change']
					}],
					cover: [{
						required: true,
						message: '封面图片不能为空!',
						trigger: ['blur', 'change']
					}],
					play_url: [{
						required: true,
						message: '短剧集数视频不能为空!',
						trigger: ['blur', 'change']
					}],
					playlet_number: [{
						required: true,
						message: '短剧集数不能为空!',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		watch: {},
		methods: {
			copyText(text) {
				console.log(text);
				clipboard.writeText(text).then(
					function() {
						that.$message({
							message: '复制成功！',
							type: 'success',
							duration: 1500
						})
					},
					function() {
						that.$message({
							message: '复制失败！',
							type: 'error',
							duration: 1500
						})
					}
				);
			},
			closeFn() {
				this.$refs.dataForm.resetFields();
				if(this.$refs.canvas){
					// 清除canvas元素和上下文的引用
					const canvas = this.$refs.canvas;
					const context = canvas.getContext('2d');
					context.clearRect(0, 0, canvas.width, canvas.height);
					// 删除canvas元素的事件监听器
					canvas.removeEventListener('click', this.handleClick);
					// 删除对canvas元素的引用
					canvas.parentNode.removeChild(canvas);
				}
			},
			//获取短剧列表
			async playletListFn() {
				const pRes = await this.$axios.get(`/api/common/playlet`);
				console.log(pRes);
				if (Array.isArray(pRes)) {
					if (pRes.length) {
						this.playletList = pRes;
						return
					}
				}
				this.playletList = [];
			},
			async downloadVideo() {
				this.innerDownloadVisible = true;
				if (this.downloadPercentage != 0) {
					that.$message({
						message: `请等待${this.playTitle}下载完`,
						type: 'error',
						customClass: 'messageClass',
						duration: 2000,
					})
					this.innerDownloadVisible = true;
					return
				}
				let play_url = (this.videoOptions.video.url).replace("http://", "https://"),
					index = play_url.lastIndexOf("."),
					download_name = this.playTitle + (play_url.substring(index, play_url.length));
				try {
					let x = new XMLHttpRequest();
					x.open("GET", play_url, true);
					x.addEventListener("progress", function(evt) {
						if (evt.lengthComputable) {
							let percentComplete = evt.loaded / evt.total;
							that.downloadPercentage = Math.floor(percentComplete * 100);
							if (that.downloadPercentage == 100) {
								that.innerDownloadVisible = false;
								that.downloadPercentage = 0;
								that.$message({
									message: `${that.playTitle||'视频'}下载成功！`,
									type: 'success',
									duration: 2000
								})
							}
						}
					}, false);
					x.responseType = 'blob';
					x.onload = function(e) {
						//会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
						let url = window.URL.createObjectURL(x.response),
							a = document.createElement('a');
						a.href = url
						a.download = download_name;
						a.click();
						a.remove();
					}
					x.send();
				} catch (error) {
					that.innerDownloadVisible = false;
					that.downloadPercentage = 0;
					that.$message({
						message: '下载视频失败！',
						type: 'error',
						duration: 2000,
					})
					console.error(error);
				}
			},
			changeSelectFn(id, field) {
				if (typeof id == 'number') {
					this.$refs.dataForm.validateField(field);
				}
			},
			lookImg(clickImg) {
				this.clickImg = clickImg;
				this.innerCoverVisible = true;
			},
			closeVideoDialogFn() {
				this.player = this.$refs.player.dp;
				console.log(this.player);
				if (this.player) {
					this.player.pause();
					this.player.seek(0);
				}
			},
			playVideo() {
				this.innerPlayVisible = true;
				this.$nextTick(() => {
					this.player = this.$refs.player.dp;
					this.player.play();
				})
			},
			async getFiles(event, fileType) {
				this['show' + fileType + 'Progress'] = false;
				console.log(event);
				const files = event.target.files;
				console.log(files);
				if (files.length) {
					const file = files[0];
					let checkRes = false;
					//图片
					if (fileType == 'images') {
						// 压缩图片后再上传
						const reader = new FileReader();
						reader.onload = (e) => {
							const img = new Image();
							img.onload = () => {
								const canvas = document.createElement('canvas');
								const ctx = canvas.getContext('2d');
								const maxWidth = 800; // 压缩后的最大宽度
								const maxHeight = 800; // 压缩后的最大高度
								let width = img.width;
								let height = img.height;
								// 如果宽度和高度超过最大值，则等比例缩放
								if (width > maxWidth || height > maxHeight) {
									const aspectRatio = width / height;
									if (width > height) {
										width = maxWidth;
										height = maxWidth / aspectRatio;
									} else {
										width = maxHeight * aspectRatio;
										height = maxHeight;
									}
								}
								canvas.width = width;
								canvas.height = height;
								ctx.drawImage(img, 0, 0, width, height);
								const compressedDataURL = canvas.toDataURL('image/jpeg',0.9); // 压缩后的图片数据URL，第二个参数表示压缩质量（0-1）
								// 将数据URL转换为Blob对象
								const blob = this.dataURLtoBlob(compressedDataURL);
								// 创建一个新的File对象
								const compressedFile = new File([blob], 'compressed_image.jpg', { type: 'image/jpeg' });
								// 在这里进行后续操作，上传压缩后的图片
								console.log(compressedFile);
								//检查文件格式和大小
								checkRes = this.checkPicFile(compressedFile, 10);
								this.uploadBefore(compressedFile,fileType,checkRes);
							};
							img.src = e.target.result;
						};
						reader.readAsDataURL(file);
					} else if (fileType == 'videos') {
						//视频
						checkRes = this.checkVideoFile(file, 500);
						this.uploadBefore(file,fileType,checkRes);
					}
				}
				event.target.value = '';
			},
			dataURLtoBlob(dataURL) {
				const byteString = atob(dataURL.split(',')[1]);
				const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
				const ab = new ArrayBuffer(byteString.length);
				const ia = new Uint8Array(ab);
				for (let i = 0; i < byteString.length; i++) {
					ia[i] = byteString.charCodeAt(i);
				}
				return new Blob([ab], {
					type: mimeString
				});
			},
			//获取上传密钥和文件路径再上传
			uploadBefore(file,fileType,checkRes){
				if (checkRes) {
					this.$axios.post(`/playlet/sts/uploadPath`, {
						type: fileType
					}).then(stsRes=>{
						if (typeof stsRes == 'object' && stsRes != null) {
							this.createOss(stsRes.token);
							this.handleUpload(file, fileType, stsRes.file_path + stsRes.file_name);
						}else{
							this.$message({
								message: '上传失败！',
								type: 'error',
								duration: 1500
							})
						}
					})
				}
			},
			handleUpload(file, fileType, uploadPath) {
				console.log('handleUploadhandleUpload');
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				console.log(this.client);
				console.log(uploadPath);
				console.log(file);
				this.client.multipartUpload(`${uploadPath}`, file, {
					progress: async function(p) {
						that['show' + fileType + 'Progress'] = true;
						that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if (typeof clientRes == 'object' && clientRes != null) {
						if (typeof clientRes.res == 'object' && clientRes.res != null) {
							if (Array.isArray(clientRes.res.requestUrls)) {
								if (clientRes.res.requestUrls.length) {
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if (!requestUrl) {
										return this.$message({
											message: '上传失败！链接为空',
											type: 'error',
											duration: 1500
										})
									}
									if (fileType == 'images') {
										this.$set(this.dataForm, this.field, requestUrl);
									} else if (fileType == 'videos') {
										let video_cover = requestUrl +
											"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
										console.log(requestUrl);
										this.$set(this.dataForm, this.field, requestUrl);
										console.log(this.dataForm);
										this.videoOptions.video.url = requestUrl;
										this.videoOptions.video.pic = video_cover;
									}
									this.$refs.dataForm.validateField(this.field);
									this['show' + fileType + 'Progress'] = false;
									return this.$message({
										message: '上传成功！',
										type: 'success',
										duration: 1500
									})
								}
							}
						}
					}
					this['show' + fileType + 'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err => {
					this['show' + fileType + 'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				this.field = field;
				this.$refs[fileBtn].click();
			},
			init() {
				this.visible = true;
				this.playletListFn();
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
				})
			},
			update(row) {
				this.visible = true;
				this.playletListFn();
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
					this.dataForm = Object.assign({}, row);
					this.videoOptions.video.url = this.dataForm.play_url;
					this.videoOptions.video.pic = this.dataForm.play_url +
						"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
				})
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(this.dataForm);
					this.$axios.post(this.playId ? `/api/playlet/episodes/update/${this.playId}` :
						'/api/playlet/episodes/create', this.dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1200,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}).catch(() => {})
				})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form {
		width: 540px;
	}

	ul {
		position: fixed;
		width: 120px;
		background-color: #fff;
		box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
		list-style: none;
		padding: 5px;
		border-radius: 3px;
		z-index: 99999;
	}

	li {
		cursor: pointer;
		padding: 5px;
	}

	.dplayer {
		height: 450px;
	}

	.innerDialog :deep(.el-dialog__header) {
		padding: 20px !important;
	}

	.innerDialog :deep(.el-dialog__body) {
		padding: 0px !important;
	}

	.innerDialog :deep(.el-dialog__headerbtn) {
		font-size: 25px !important;
	}
</style>